package com.example.image.glide

import android.content.Context
import android.os.Environment
import com.bumptech.glide.Glide
import com.bumptech.glide.GlideBuilder
import com.bumptech.glide.Registry
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory
import com.bumptech.glide.load.engine.cache.LruResourceCache
import com.bumptech.glide.load.engine.cache.MemorySizeCalculator
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.module.AppGlideModule
import okhttp3.Cache
import okhttp3.OkHttpClient
import java.io.File
import java.io.InputStream

/**
 * 自定义Glide模块
 */
@GlideModule
class CustomGlideModule:AppGlideModule() {
    /**
     * 自定义Glide内存和磁盘的缓存策略
     */
    override fun applyOptions(context: Context, builder:GlideBuilder){
        //计算使用多大的内存空间
        val glideMemorySize = MemorySizeCalculator.Builder(context).build().memoryCacheSize / 6L
        //设置内存大小(默认为当前APP内存的1/8)
        builder.setMemoryCache(LruResourceCache(glideMemorySize))
        //设置磁盘大小(默认250M)
        builder.setDiskCache(InternalCacheDiskCacheFactory(context,"glide_disk_cache",300*1024*1024))
    }

    /**
     * 自定义网络缓存大小
     * Glide网络请求采用OKHttp实现
     */
    override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
        try {
            val builder = OkHttpClient.Builder()
            //先考虑外部SD卡,如果没有再考虑内存SD卡
            val externalDir = Environment.getExternalStorageDirectory()
            val cacheDir = if(externalDir.exists()){
                "${externalDir.absolutePath}/glideCache"//外置SD卡
            }else{
                "${context.externalCacheDir?.absolutePath}/glideCache"//内置SD卡
            }
            val cacheFile = File(cacheDir)
            //计算一下缓存大小
            var cacheSize = 50 * 1024 * 1024L
            if(externalDir.exists() && externalDir.totalSpace > 0L){
                cacheSize = externalDir.totalSpace / 8L
            }else{
                cacheSize = context.externalCacheDir?.totalSpace?.div(8L) ?: 10 * 1024 *1024L
            }
            val networkCache = Cache(cacheFile,cacheSize)

            //设置网络缓存目录
            builder.cache(networkCache)
            val newOkHttpClient = builder.build()
            registry.replace(GlideUrl::class.java,InputStream::class.java,OkHttpUrlLoader.Factory(newOkHttpClient))
        }catch (e:Exception){
            e.printStackTrace()
        }
    }
}